var request = require('request');
var Promise = require('bluebird');
var iconv = require('iconv-lite');

module.exports = {
  requestData: requestData,
  requestBufferData: requestBufferData,
  postBufferData: postBufferData
};


function requestData(url) {
  return new Promise(function (resolve, reject) {

    console.log('requestData: ' + url);
    request(url, function(err, res, data) {

      if(err || res.statusCode != 200) {
        console.log(err);
        reject(err);
      } else {

        resolve(data);

      }
    });
  });
}

function requestBufferData(url, encoding) {
  return new Promise(function (resolve, reject) {

    console.log('requestBufferData: ' + url);
    request({encoding: null, url: url}, function(err, res, data) {

      if(err || res.statusCode != 200) {
        console.log(err);
        reject(err);
      } else {

        resolve(iconv.decode(data, encoding).toString());

      }
    });
  });
}

function postBufferData(option, encoding) {
  return new Promise(function (resolve, reject) {
    
    console.log('postBufferData: ' + option.url);
    request.post(option, function(err, res, data){

      if(err || res.statusCode != 200) {
        console.log(err);
        reject(err);
      } else {

        resolve(iconv.decode(data, encoding).toString());

      }
    });
  });
}
